package com.wrl.mmall.service.impl;

import com.wrl.mmall.common.Const;
import com.wrl.mmall.common.ServerResponse;
import com.wrl.mmall.dao.UserMapper;
import com.wrl.mmall.pojo.User;
import com.wrl.mmall.service.IUserService;
import com.wrl.mmall.util.MD5Util;
import com.wrl.mmall.util.RedisShardedPoolUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.UUID;

/**
 * Created by Wang Renlei on 2018/8/22.
 */
@Slf4j
@Service("iUserService")
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserMapper userMapper;

    //登陆
    @Override
    public ServerResponse<User> login(String username, String password) {
        log.info("UserServiceImpl.login");
        //检查注册用户名是否存在
        int resultCount = userMapper.checkUsername(username);
        if (resultCount == 0) {
            return ServerResponse.createByErrorMessage("用户名不存在");
        }
        //密码登陆MD5
        String passwordMD5 = MD5Util.MD5EncodeUtf8(password);
        User user = userMapper.selectLogin(username, passwordMD5);
        if (user == null) {
            return ServerResponse.createByErrorMessage("密码错误");
        }
        //设置密码加密
        user.setPassword(StringUtils.EMPTY);
        return ServerResponse.createBySuccess("登陆成功", user);
    }

    //注册
    @Override
    public ServerResponse<String> registerUser(User user) {
        /* //已抛弃，使用checkValid方法校验
        //检查注册用户名是否存在
        int resultCount = userMapper.checkUsername(user.getUsername());
        if(resultCount > 0){
            return ServiceResponse.createByErrorMessage("用户名已存在");
        }
        //邮箱是否重复
        resultCount = userMapper.checkEmail(user.getUsername());
        if(resultCount > 0){
            return ServiceResponse.createByErrorMessage("用户名已存在");
        }*/
        ServerResponse validResponse = this.checkValid(user.getUsername(), Const.USERNAME);
        if (!validResponse.isSuccess()) {
            return validResponse;
        }
        validResponse = this.checkValid(user.getEmail(), Const.EMAIL);
        if (!validResponse.isSuccess()) {
            return validResponse;
        }
        //到了这里说明验证成功，可以注册了

        //默认把角色设置成一个普通用户
        user.setRole(Const.Role.ROLE_CURRENT);
        //密码加密，然后保存到数据库
        user.setPassword(MD5Util.MD5EncodeUtf8(user.getPassword()));
        int resultCount = userMapper.insert(user);
        if (resultCount == 0) {
            return ServerResponse.createByErrorMessage("注册失败");
        }
        return ServerResponse.createBySuccessMessage("注册成功");
    }

    @Override
    public ServerResponse<String> selectQuestion(String username) {
        ServerResponse validResponse = this.checkValid(username, Const.USERNAME);
        if (validResponse.isSuccess()) {
            //用户不存在
            return ServerResponse.createByErrorMessage("用户不存在");
        }
        String question = userMapper.selectQuestionByUsername(username);
        if (StringUtils.isNotBlank(question)) {
            return ServerResponse.createBySuccessMessage(question);
        }
        return ServerResponse.createByErrorMessage("该用户未设置找回密码的问题");
    }

    @Override
    public ServerResponse<String> forgetCheckAnswer(String username, String question, String answer) {
        if (this.checkValid(username, Const.USERNAME).isSuccess()) {
            return ServerResponse.createByErrorMessage("用户不存在");
        }
        int resultCount = userMapper.checkAnswer(username, question, answer);
        if (resultCount > 0) {
            //说明这个问题答案是这个用户的，并且正确
            //声明token
            String forgetToken = UUID.randomUUID().toString();
            RedisShardedPoolUtil.setEx(Const.TOKEN_PREFIX + username, forgetToken, 60 * 60 * 12);
            return ServerResponse.createBySuccess(forgetToken);
        }
        return ServerResponse.createByErrorMessage("问题的答案错误");
    }


    @Override
    public ServerResponse<String> forgetResetPassword(String username, String password, String forgenToken) {
        if (StringUtils.isBlank(forgenToken)) {
            return ServerResponse.createByErrorMessage("参数错误，token需要传递");
        }
        if (this.checkValid(username, Const.USERNAME).isSuccess()) {
            return ServerResponse.createByErrorMessage("用户不存在");
        }
        String token = RedisShardedPoolUtil.get(Const.TOKEN_PREFIX + username);
        if (StringUtils.isBlank(token)) {
            return ServerResponse.createByErrorMessage("token无效或过期");
        }
        if (StringUtils.equals(forgenToken, token)) {
            String md5Password = MD5Util.MD5EncodeUtf8(password);
            int count = userMapper.updatePasswordByUsername(username, md5Password);
            if (count > 0) {
                //密码修改成功，删除token
                RedisShardedPoolUtil.del(Const.TOKEN_PREFIX + username);
                return ServerResponse.createBySuccessMessage("修改密码成功");
            }
        } else {
            return ServerResponse.createByErrorMessage("token错误，请重新获取重置密码的token");
        }
        return ServerResponse.createByErrorMessage("修改密码失败 ");
    }

    @Override
    public ServerResponse<String> resetPassword(String oldPassword, String newPassword, User user) {
        //防止横向越权，要检验这个用户的旧密码,一定要指定这个用户
        int count = userMapper.checkPassword(MD5Util.MD5EncodeUtf8(oldPassword), user.getId());
        if (count == 0) {
            return ServerResponse.createByErrorMessage("旧密码输入错误");
        }
        user.setPassword(MD5Util.MD5EncodeUtf8(newPassword));
        int updateCount = userMapper.updateByPrimaryKeySelective(user);
        if (updateCount > 0) {
            return ServerResponse.createBySuccessMessage("密码更新成功");
        }
        return ServerResponse.createByErrorMessage("密码更新错误");
    }

    @Override
    public ServerResponse<User> updateUserInfo(User user) {
        //userName不能被更新，email要被校验
        //email也要进行校验 校验新的email是不是已经存在，并且存在的email如果相同,不能是我们当前用户的
        int emailCount = userMapper.checkEmailByUserId(user.getEmail(), user.getId());
        if (emailCount > 0) {
            return ServerResponse.createByErrorMessage("Email已经存在，请更换Email");
        }
        //创建一个user，单独设置要更新的属性
        User u = new User();
        u.setId(user.getId());
        u.setEmail(user.getEmail());
        u.setPhone(user.getPhone());
        u.setQuestion(user.getQuestion());
        u.setAnswer(user.getAnswer());
        u.setUpdateTime(new Date());
        int updateCount = userMapper.updateByPrimaryKeySelective(u);
        if (updateCount > 0) {
            return ServerResponse.createBySuccess("更新个人信息成功", u);
        }
        return ServerResponse.createByErrorMessage("更新个人信息失败");
    }

    @Override
    public ServerResponse<User> getUserInformation(Integer userId) {
        User user = userMapper.selectByPrimaryKey(userId);
        if (user == null) {
            return ServerResponse.createByErrorMessage("找不到当前用户");
        }
        user.setPassword(StringUtils.EMPTY);
        return ServerResponse.createBySuccess(user);
    }


    //校验的方法
    @Override
    public ServerResponse<String> checkValid(String str, String type) {
        if (StringUtils.isNotBlank(type)) {
            //验证数据库里面是否有这个用户名
            if (Const.USERNAME.equals(type)) {
                int resultCount = userMapper.checkUsername(str);
                if (resultCount > 0) {
                    return ServerResponse.createByErrorMessage("用户名已存在");
                }
            }
            //验证数据库里面是否有这个Email
            if (Const.EMAIL.equals(type)) {
                int resultCount = userMapper.checkEmail(str);
                if (resultCount > 0) {
                    return ServerResponse.createByErrorMessage("Email已存在");
                }
            }
        } else {
            return ServerResponse.createByErrorMessage("参数错误");
        }
        return ServerResponse.createBySuccessMessage("校验成功");
    }


    //backend

    /**
     * 校验是否是管理员
     *
     * @param user
     * @return
     */
    @Override
    public ServerResponse checkAdminRole(User user) {
        if (user != null && user.getRole().intValue() == Const.Role.ROLE_ADMIN) {
            return ServerResponse.createBySuccess();
        }
        return ServerResponse.createByError();
    }


}
